<?php

use App\Models\AdminConfig;
use Illuminate\Support\Arr;
/**
 * 公共函数定义文件
 */

if (!function_exists("json_msg")) {
	/**
	 * 返回带code,msg,data得json
	 * @param  int|integer $code [返回码 0成功 400及以上失败]
	 * @param  string      $msg  [提示信息，必须直观]
	 * @param  [type]      $data [返回数据]
	 * @return [type]            [json]
	 */
	function json_msg(int $code = 0, string $msg = "请求成功", $data = null) {
		return response()->json(array("data" => $data, "msg" => $msg, "code" => $code));
	}
}
if (!function_exists("picture_server")) {
	/**
	 * 获取当前服务器上传域名目录
	 * @return [type]            [string]
	 */
	function picture_server() {
		return config("filesystems.disks." . env("FILESYSTEM_DRIVER") . '.url');
	}
}
if (!function_exists("picture_server_parse_array")) {
	/**
	 * 批量替换图片服务器
	 * @return [type]            [string]
	 */
	function picture_server_parse_array(array $arr = [], string $field = "") {
		if (!empty($arr)) {
			$url = config("filesystems.disks." . env("FILESYSTEM_DRIVER") . '.url');

			foreach ($arr as $key => $val) {
				if (isset($val[$field]) && gettype($val[$field]) == 'string') {
					$arr[$key][$field] = $url . $val[$field];
				}
			}
		}
		return $arr;
	}
}

if (!function_exists('request_domain')) {
	/**
	 * [当前请求域名]
	 * @param  boolean $port [是否携带端口]
	 * @return [string]        [带协议的域名]
	 */
	function request_domain($port = false) {
		$url = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'];
		if (($_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != '443') && $port) {
			$url .= $_SERVER['SERVER_PORT'] . ":" . $_SERVER['SERVER_PORT'];
		}
		return $url;
	}
}
if (!function_exists('curl_send')) {
	/**
	 * [发送curl请求]
	 * @param  string $url    [请求链接]
	 * @param  array  $data   [POST参数，不传为GET]
	 * @param  array  $header [请求Header]
	 * @return [type]         [false表示失败]
	 */
	function curl_send(string $url = '', array $data = [], array $header = []) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_URL, $url);
		// $header=[
		//      'Content-Type:'.'application/x-www-form-urlencoded; charset=UTF-8'
		// ];
		if (!empty($header)) {
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
			curl_setopt($ch, CURLOPT_HEADER, 0); //返回response头部信息
		}
		if (!empty($data)) {
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		// curl_setopt($ch, CURLOPT_SSLVERSION, 1);
		// if (defined('CURL_SSLVERSION_TLSv1')) {
		//  curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
		// }
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		$rs = curl_exec($ch);
		if (curl_errno($ch)) {
			//出错则显示错误信息
			//var_dump( curl_error($ch) );
			return false;
		} else {
			curl_close($ch);
			$arr = json_decode($rs, true);
			if ($arr) {
				return $arr;
			}
			return $rs;

		}
	}
}

if (!function_exists('sys_config')) {
	/**
	 * 获取系统配置表配置
	 * @Author MrGuo
	 * @Date   2020-08-07
	 * @param  string     $key [字段名]
	 * @return [type]          [description]
	 */
	function sys_config(string $key = '') {
		$config = AdminConfig::getConfig($key);
		return $config;
	}
}
if (!function_exists('sys_config_group')) {
	/**
	 * 获取系统配置表配置
	 * @Author MrGuo
	 * @Date   2020-08-07
	 * @param  string     $key [字段名]
	 * @return [type]          [description]
	 */
	function sys_config_group(string $key = '') {
		$config = AdminConfig::getConfigByGroup($key);
		return $config;
	}
}
if (!function_exists('rand_string')) {
	/**
	 * 生成随机字符串
	 * @param int $length 生成长度
	 * @param int $type 生成类型：0-小写字母+数字，1-小写字母，2-大写字母，3-数字，4-小写+大写字母，5-小写+大写+数字
	 * @author 蔡伟明 <314013107@qq.com>
	 * @return string
	 */
	function rand_string($length = 8, $type = 5) {
		$a = 'abcdefghijklmnopqrstuvwxyz';
		$A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$n = '0123456789';

		switch ($type) {
		case 1:$chars = $a;
			break;
		case 2:$chars = $A;
			break;
		case 3:$chars = $n;
			break;
		case 4:$chars = $a . $A;
			break;
		case 5:$chars = $a . $A . $n;
			break;
		default:$chars = $a . $n;
		}

		$str = '';
		for ($i = 0; $i < $length; $i++) {
			$str .= $chars[mt_rand(0, strlen($chars) - 1)];
		}
		return $str;
	}
}

if (!function_exists('format_bytes')) {
	/**
	 * 格式化字节大小
	 * @param  number $size      字节数
	 * @param  string $delimiter 数字和单位分隔符
	 * @return string            格式化后的带单位的大小
	 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
	 */
	function format_bytes($size, $delimiter = '') {
		$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
		for ($i = 0; $size >= 1024 && $i < 5; $i++) {
			$size /= 1024;
		}

		return round($size, 2) . $delimiter . $units[$i];
	}
}

if (!function_exists("array_field_sort")) {
	/**
	 * 二维数组根据某个字段进行重新排序
	 * @Author MrGuo           <gj2517@qq.com>
	 * @param  array           $arr            [数组]
	 * @param  string          $field          [要排序的字段]
	 * @param  string          $desc           [排序方式 desc, asc]
	 * @param  boolval|boolean $number         [是否重置键名为数字]
	 * @return [array]
	 */
	function array_field_sort(array $arr = [], string $field = '', string $desc = "desc", $number = false) {
		$arr2 = [];
		foreach ($arr as $k => $v) {
			if (isset($v[$field])) {
				if (isset($arr2[$v[$field]])) {
					$arr2[$v[$field] . "." . $k] = $v;
				} else {
					$arr2[$v[$field]] = $v;
				}
			} else {
				$arr2[$k] = $v;
			}
		}
		if (strtoupper($desc) == "DESC") {
			krsort($arr2);
		} else {
			ksort($arr2);
		}
		if ($number) {
			$arr3 = [];
			foreach ($arr2 as $k => $v) {
				array_push($arr3, $v);
			}
			return $arr3;
		}
		return $arr2;
	}
}

if (!function_exists('get_client_ip')) {
	/**
	 * 获取客户端IP地址
	 * @return mixed
	 */
	function get_client_ip() {
		if (isset($_SERVER)) {
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
			} else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
				$ip = $_SERVER['HTTP_CLIENT_IP'];
			} else {
				$ip = $_SERVER['REMOTE_ADDR'];
			}
		} else {
			if (getenv('HTTP_X_FORWARDED_FOR')) {
				$ip = getenv('HTTP_X_FORWARDED_FOR');
			} else if (getenv('HTTP_CLIENT_IP')) {
				$ip = getenv('HTTP_CLIENT_IP');
			} else {
				$ip = getenv('REMOTE_ADDR');
			}
		}
		// IP地址合法验证
		if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
			return $ip;
		}
		return 'Unknown';
	}
}

if (!function_exists("yunxin_sms")) {
	/**
	 * 发送短信
	 * @return [type] [description]
	 */
	function yunxin_sms(string $mobile, string $msg, int $channel = 0) {

		$url = 'http://120.55.197.77:1210/Services/MsgSend.asmx/SendMsg';
		$data = [
			'userCode' => sys_config("yunxin_user_code"),
			'userPass' => sys_config("yunxin_user_pass"),
			"Channel" => $channel,
		];
		$data['Msg'] = $msg;
		$data['DesNo'] = $mobile;

		$ch = curl_init();
		$header = [
			'Content-Type:application/x-www-form-urlencoded',
		];

		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_HEADER, 0); //返回response头部信息

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

		if (!empty($data)) {
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		$rs = curl_exec($ch);
		$xml = json_decode(json_encode(simplexml_load_string($rs)), true);
		$msg = "发送成功";
		switch ($xml[0]) {
		case '-3':
			$msg = "用户名密码错误或者用户无效";
			break;
		case '-5':
			$msg = "签名不正确";
			break;
		case '-6':
			$msg = "含有敏感关键字";
			break;
		case '-7':
			$msg = "余额不足";
			break;
		case '-8':
			$msg = "没有可用的通道，或不在时间范围内";
			break;
		case '-9':
			$msg = "发送号码一次不能超过1000个";
			break;
		case '-10':
			$msg = "号码数量大于允许上限";
			break;
		case '-11':
			$msg = "号码数量小于允许下限";
			break;
		default:
			# code...
			break;
		}
		$err_code = intval($xml[0]);
		if ($err_code > 1000) {
			return true;
		} else {
			return false;
		}

	}
}